package com.hoshiicloud.user;

import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static java.util.stream.Collectors.joining;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author linjx on 2019/6/28
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class BaseTest1 {
    @Autowired
    private WebApplicationContext ctx;
    private final String url="http://localhoust:10011/";

    public MockMvc mockMvc;

    /**
     * 初始化MVC的环境
     */
    @Before
    public void before() {
        mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
    }


    public void getTest(String method, String param) throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get(url+method+"/"+param)).andExpect(status().isOk()).andDo(print());
    }

    /**
     *  根据多个id查询信息
     * @param method 请求url
     * @param name 接收参数名称
     * @param list 请求参数集合
     * @throws Exception
     */
    public void getMoreTest(String method, String name, List<Long> list) throws Exception {
        String ids = list.stream().map(c -> "&"+name+"="+c).collect(joining()).substring(1);
        mockMvc.perform(MockMvcRequestBuilders.get(url+method+"?"+ids)).andExpect(status().isOk()).andDo(print());
    }

    public void deleteTest(String method, String param) throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.delete(url+method+"/"+param)).andExpect(status().isOk()).andDo(print());
    }

    public void postTest(String method, String content) throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post(url+method).content(content).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andDo(print());
    }

    public void putTest(String method, String content) throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.put(url+method).content(content).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andDo(print());
    }

    public void postValuesTeset(String method, Map<String, Object> map) throws Exception{
        Set<String> keys = map.keySet();
        String str = keys.stream().map(s -> "&" + s + "=" + map.get(s)).collect(joining()).substring(1);
        mockMvc.perform(MockMvcRequestBuilders.post(url+method+"?"+str)).andExpect(status().isOk()).andDo(print());
    }

}